package com.xqboss.task.listener;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.xqboss.common.constant.CacheConstants;
import com.xqboss.common.core.domain.entity.SysUser;
import com.xqboss.common.core.redis.RedisCache;
import com.xqboss.common.utils.StringUtils;
import com.xqboss.task.socket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.Message;
import org.springframework.data.redis.connection.MessageListener;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.stereotype.Service;

import java.sql.PreparedStatement;
import java.sql.SQLException;

/**
 * websocket 用户在线状态监听
 */
@Service
@Slf4j
public class WsOnlineListener implements MessageListener {

    @Override
    public void onMessage(Message message, byte[] pattern) {
        try {
            byte[] body = message.getBody();
            String data = RedisSerializer.string().deserialize(body);
            if (StringUtils.isNotEmpty(data)) {
                JSONObject json = JSON.parseObject(data);
                Long userId = json.getLong("userId");
                Boolean isOnline = json.getBoolean("isOnline");
                SqlRunner sqlRunner = new SqlRunner();
                boolean update = sqlRunner.update("update sys_user set is_online = " + isOnline + " where user_id = " + userId);
                if (update) {
                    log.info("用户{}在线状态更新为：{}",userId, isOnline?"上线":"离线");
                }else{
                    log.error("用户{}在线状态更新失败！",userId);
                }
            }
        } catch (Exception e) {
            log.error("用户在线状态更新失败!", e);
        }
    }
}
